package com.changcheng.controller;

import com.alibaba.fastjson.JSON;
import com.changcheng.aspect.ServiceOperation;
import com.changcheng.pojo.*;
import com.changcheng.pojo.Do.*;
import com.changcheng.service.UserService;
import com.changcheng.utils.VerifyUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;

/**
 * @author xuan
 * @create 2021--04--13
 */
@RestController
@Api(tags = "用户操作相关接口")
//@RequestMapping("/user1")
public class UserController {
    @Autowired

    private UserService service;


    //登录
    @ApiOperation(value = "登录")
    @PostMapping("/login")//参数username账号，password密码，verifyCode验证码
    @ServiceOperation("登录")
    public String login(@RequestBody userDo login,
                        HttpSession session) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(login.getUsername(), login.getPassword());
        String code = (String) session.getAttribute("verifyCode");
//        String code = "1";
        System.out.println(code);
        try {


            if (login.getVerifyCode().equalsIgnoreCase(code)) {
                subject.login(token);
                return "success";
            } else {
                //验证码错误
                return "verifyError";
            }
        } catch (UnknownAccountException e) {
            //账号错误
            return "usernameError";
        } catch (IncorrectCredentialsException e) {
            //密码错误
            return "passwordError";
        }
    }

    //未授权

    @GetMapping("/noauth")
//    @RequestMapping("/noauth")
    public String unauthorized() {
        return "未经授权无法访问此界面";
    }

    //验证码
    @ApiOperation(value = "验证码")
    @GetMapping("/getVerifyCode")
//    @RequestMapping("/getVerifyCode")
    public void getVerifyaddCode(HttpServletResponse response, HttpServletRequest request) throws IOException {
        // 生成默认的验证码图片
        try {
            int width = 200;
            int height = 69;

            BufferedImage verifyImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);//生成对应宽高的初始图片
            String randomText = VerifyUtil.drawRandomText(width, height, verifyImg);//单独的一个类方法，出于代码复用考虑，进行了封装。功能是生成验证码字符并加上噪点，干扰线，返回值为验证码字符

            request.getSession().setAttribute("verifyCode", randomText);
            response.setContentType("image/png");//必须设置响应内容类型为图片，否则前台不识别

            OutputStream os = response.getOutputStream(); //获取文件输出流
            ImageIO.write(verifyImg, "png", os);//输出图片流
            os.flush();
            os.close();//关闭流
            System.out.println(randomText);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //退出
    @ApiOperation(value = "登出")
    @GetMapping("/users/logout")
//    @RequestMapping("/user/logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "success";
    }

    @ApiOperation(value = "查询权限数据库表")
    @GetMapping("/users/findAllRole")
//    @RequestMapping("/user/findAllRole")
    public List<Role> findAllRole() {
        return service.findAllRole();
    }

    //注册
    @ApiOperation(value = "注册")
    @PostMapping("/users/register")//username,password,name,roleId
    public String register(@RequestBody RegisterDo register) {
        //先判断是否是超级管理员
        HashMap<String,Object> res=new HashMap<>();
        if (findCurrentUserRole().equals("1")) {

        User user = new User();
        user.setUsername(register.getUsername());
        user.setName(register.getName());

        SimpleHash md5 = new SimpleHash("MD5", "123", register.getPassword(), 1024);
        user.setPassword(md5.toString());
        service.addUser(user, register.getRoleId());
        res.put("flag",0);
        }
        else {
            res.put("flag",1);
//            model.addAttribute("msg","出错啦！该操作为超级管理员才可以");
        }
        return JSON.toJSONString(res);
    }
    //获取当前用户信息
    //    @RequestMapping("/user/getUser")
    @ApiOperation(value = "获取当前用户信息")
    @GetMapping("/users/getUser")
    public User getUser() {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        String name = user.getUsername();
        System.out.println(name);
        return user;
    }

    /*@ApiOperation(value = "添加用户")
    @GetMapping("/users/addUser")
    public void addUser(User user, int roleId) {
        Subject subject = SecurityUtils.getSubject();
        service.addUser();
    }*/

    @ApiOperation(value = "更改密码")
    @PutMapping("/users/update")
    @ServiceOperation("更改密码")
    public String update(@RequestBody PasswordDO password) {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        SimpleHash md5Password = new SimpleHash("MD5", password.getOldPassword(), user.getUsername(), 1024);
        if (md5Password.toString().equals(user.getPassword())) {
            if (password.getNewPasswordOne().equals(password.getNewPasswordTwo())) {
                //插入正确密码
                SimpleHash md5newPassword = new SimpleHash("MD5", password.getNewPasswordOne(), user.getUsername(), 1024);
                service.updatePassword(md5newPassword.toString(), user.getUsername());
                return "success";

            } else {

                return "equalError";
            }
        } else {

            return "oldPasswordError";
        }

    }

    @ApiOperation("查询所有用户及权限")
    @PostMapping("/users/findAllUser")
    public String select(@RequestBody PageInfo pageInfo){
        HashMap<String,Object> res=new HashMap<>();
        pageInfo.setRemoveItem((pageInfo.getPage()-1)* pageInfo.getSumItem());//这是一句垃圾代码，但请不要动他
        List<User> users = service.findAllUser(pageInfo);
        //如果查询结果不为空
        if(users.size()>0){
            res.put("flag",0);
            res.put("data",users);
        }
        //如果查询结果为空
        else{
            res.put("flag",1);
        }
        return JSON.toJSONString(res);

    }

    @ApiOperation("查询用户的总个数(用于分页)")
    @GetMapping("/users/selectItemsNumber")
    public int selectItemsNumber(){
        return service.selectItemsNumber();
    }

    //查询当前登录用户权限
    @ApiOperation(value = "查询当前用户的权限")
    @GetMapping("/users/findCurrentUserRole")
    public String findCurrentUserRole() {

        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        int role = user.getId();
        //返回结果集
        List<String> currentUserRole = service.findCurrentUserRole(role);
        //去掉中括号
        String s1 = StringUtils.strip(currentUserRole.toString(), "[]");//第一个参数放集合，第二个参数去掉中括号"[]"
        return s1;
    }


    @ApiOperation(value = "更改他人密码")
    @PutMapping("/users/updateUserPassword")
    @ServiceOperation("更改他人密码")
    public String updateUserPassword(@RequestBody ElsePasswordDo password, Model model) {
        //先判断是否是超级管理员
        HashMap<String,Object> res=new HashMap<>();
        if (findCurrentUserRole().equals("1")) {
            SimpleHash md5Password = new SimpleHash("MD5", password.getPassword(), password.getUsername(), 1024);
            Boolean aBoolean = service.updatePassword(md5Password.toString(), password.getUsername());
            if (aBoolean){
            res.put("flag",0);}
        }
        else {
            res.put("flag",1);
//            model.addAttribute("msg","出错啦！该操作为超级管理员才可以");
        }

        return JSON.toJSONString(res);

    }

    @ApiOperation(value = "删除user")
    @PostMapping(value = "/users/deleteUser")
//    @RequestMapping(value="/user/deleteUser")
    public String deleteUser(int id ,Model model) {
        //先判断是否是超级管理员
        HashMap<String,Object> res=new HashMap<>();
        if (findCurrentUserRole().equals("1")) {
            Boolean delete = service.deleteUser(id);
            if (delete){
            res.put("flag",0);
            }
       }
       else {
           res.put("flag",1);
//           model.addAttribute("msg","出错啦!");
       }
        return JSON.toJSONString(res);
    }

   //权限管理


}
